<template>
	<view>
		<u-navbar z-index="100" :title="multi?'选择多个聊天':'选择一个聊天'" :border-bottom="false">
			<view slot="right" class="u-m-r-30">
				<view v-if="choose.length&&multi" class="u-p-x-20 u-p-y-8 radius bg-blue u-font-28" @tap="submit">发送({{choose.length}})</view>
				<view v-else-if="multi" class="u-font-28" @tap="switchMulti">单选</view>
				<view v-else-if="!multi" class="u-font-28" @tap="switchMulti">多选</view>
			</view>
		</u-navbar>
		<view class="search-mimicry">
			<view class="search-bar">
				<view class="search">
					<view class="icon u-font-36 text-gray iconfont icon-sousuo"></view>
					<input class="input" type="text" v-model="search.keyword" placeholder-class="text-gray" placeholder="搜索" auto-focus>
					<text v-if="search.keyword" class="clear u-m-l-30 u-font-36 text-grey iconfont icon-failfill" @tap="search.keyword=''"></text>
				</view>
				<view v-if="multi" class="all-in" @tap="allIn">
					全选
				</view>
			</view>
		</view>
		<view v-show="!search.keyword">
			<view class="group u-p-x-30 u-p-y-20" v-for="item in convList" :key="item.id" @tap="pickConv(item)">
				<view v-if="multi" class="checkbox u-m-r-30" :class="{checked:item.checked}">
				</view>
				<view class="group-avatar u-m-r-20">
					<u-avatar :src="item.avatar" mode="square"></u-avatar>
				</view>
				<view class="group-content u-flex">
					<text class="u-line-1 u-font-32">{{item.remarks||item.name}}</text>
				</view>
			</view>
		</view>
		<view v-show="search.keyword">
			<view v-show="friendList.length" class="friend-box" :class="{fold:fold}">
				<view class="bg-f5 u-p-x-30 u-p-y-10">
					<text class="u-font-28">好友</text>
				</view>
				<view class="group u-p-x-30 u-p-y-20" v-for="item in friendList" :key="item.id" @tap="pickFriend(item)">
					<view v-if="multi" class="checkbox u-m-r-30" :class="{checked:item.checked}">
					</view>
					<view class="group-avatar u-m-r-20">
						<u-avatar :src="item.avatarUrl" mode="square"></u-avatar>
					</view>
					<view class="group-content u-flex">
						<view class="u-font-32 u-line-1">
							<light-text :char="search.keyword" :word="item.remarks||item.userName"></light-text>
						</view>
						<!-- <light-text :char="search.keyword" :word="item.userName"></light-text>								<text class=" ">{{item.userName}}</text> -->
					</view>
				</view>
				<view class="u-flex u-row-between u-p-y-20 u-p-x-30" v-if="friendList.length>3" @tap="fold=!fold">
					<text class="u-font-28 text-blue">{{fold?'更多好友':'收起'}}</text>
					<text class="iconfont u-font-28" :class="{'icon-arrow-down':fold,'icon-arrow-up':!fold}"></text>
				</view>
			</view>
			<view v-show="groupList.length">
				<view class="bg-f5 u-p-x-30 u-p-y-10">
					<text class="u-font-28">群聊</text>
				</view>
				<view class="group u-p-x-30 u-p-y-20" v-for="item in groupList" :key="item.id" @tap="pickGroup(item)">
					<view v-if="multi" class="checkbox u-m-r-30" :class="{checked:item.checked}">
					</view>
					<view class="group-avatar u-m-r-20">
						<u-avatar :src="item.avatar" mode="square"></u-avatar>
					</view>
					<view class="group-content u-flex">
						<view class="u-font-32 u-line-1">
							<light-text :char="search.keyword" :word="item.name"></light-text>
						</view>
					</view>
				</view>
			</view>
			<view v-show="!groupList.length&&!friendList.length" class="u-text-center u-font-28 u-p-30">
				<text>没有找到"</text>
				<text class="text-blue">{{search.keyword}}</text>
				<text>"相关结果</text>
			</view>
		</view>
	</view>
</template>

<script>
	import chat from "@/IM/index.js"
	import {mapGetters,mapActions} from "vuex"
	import { ConversationType } from "@/entity/ConversationType";
	import { toast } from "@/utils/util";
	import lightText from "@/components/lightText/lightText.vue"
	export default {
		components:{
			lightText
		},
		data() {
			return {
				search:{
					show:false,
					keyword:'',
				},
				fold:true,
				multi:false,
				page:{
					startTime:'',
					pageSize:10,
					loading:false,
					nomore:false
				},
				choose:[],
				msg:null,
				lock:false,
				event:null
			};
		},
		computed:{
			...mapGetters('user',['userInfo']),
			...mapGetters('chat',['conversations']),
			...mapGetters('addr',['friends','groups']),
			convList(){
				return this.conversations.map((item)=>{
					return{
						...item,
						checked:this.choose.some((id)=>id==item.id)
					}
				})
			},
			friendList(){
				return this.friends.filter(({userName,remarks})=>remarks.includes(this.search.keyword)||userName.includes(this.search.keyword)).map((item)=>({...item,checked:this.choose.some((id)=>id==item.userId)}))
			},
			groupList(){
				return this.groups.filter(({name})=>name.includes(this.search.keyword)).map((item)=>({...item,checked:this.choose.some((id)=>id==item.id)}))
			}
		},
		onLoad() {
			const event = this.getOpenerEventChannel();
			event.on('init',(msg)=>{
				this.msg = msg
			})
			this.event = event
		},
		onReachBottom() {
			this.moreConv()
		},
		methods:{
			...mapActions('chat',['fetchConversationList','sendMessage','saveHistory','setConversation']),
			openSearch(){
				this.search.show = true
				this.search.keyword = ''
			},
			closeSearch(){
				this.search.show = false
			},
			
			async moreConv(){
				if(this.page.loading){
					throw new Error('正在请求中')
				}
				try{
					this.page.loading = true
					if(this.page.nomore){
						return []
					}
					const convs = await this.fetchConversationList(this.page)
					if(!convs||convs.length<this.page.pageSize){
						this.page.nomore = true
					}else{
						const last = convs.slice(-1)[0]
						this.page.startTime = last.lastTime
					}
				}finally{
					this.page.loading = false
				}
			},
			
			async sendMsg(conv){
				const {at,...extras} = this.msg.extras
				const msg = chat.createMessage({
					chatType:conv.type,
					content: this.msg.content,
					msgType: this.msg.msgType,
					extras
				})
				if(ConversationType.Single==conv.type){
					msg.to = conv.id
					msg.readBody = {readCount:0,unreadCount:1}
				}
				if(ConversationType.Group==conv.type){
					msg.groupId = conv.id
					const group = this.groups.find((item)=>item.id==conv.id)
					msg.readBody = {readCount:0,unreadCount:group.userCount-1}
				}
				msg.avatar = this.userInfo.avatarUrl
				msg.nick = this.userInfo.userName
				msg.status = 'loading';
				msg.errMsg = ''
				try{
					await this.sendMessage({
						message: msg,
						id: conv.id
					})
					await chat.send(msg)
					uni.$emit('chat_receive',conv.id,msg)
					msg.status = 'success';
					this.saveHistory()
				}catch(e){
					msg.status = 'error';
					msg.errMsg = e.message
					toast(e.message)
					throw e
				}
			},
			
			async pickConv(conv){
				if(conv.checked){
					this.choose = this.choose.filter(item=>item!=conv.id)
				}else{
					this.choose.push(conv.id)
				}
				if(!this.multi){
					this.submit()
				}
			},
			async pickFriend(friend){
				if(friend.checked){
					this.choose = this.choose.filter(item=>item!=friend.userId)
				}else{
					this.choose.push(friend.userId)
				}
				if(!this.multi){
					this.submit()
				}
			},
			async pickGroup(group){
				if(group.checked){
					this.choose = this.choose.filter(item=>item!=group.id)
				}else{
					this.choose.push(group.id)
				}
				if(!this.multi){
					this.submit()
				}
			},
			switchMulti(){
				this.multi = !this.multi
				this.choose = []
			},
			allIn(){
				if(this.search.keyword){
					this.friendList.forEach((item)=>{
						!item.checked&&this.choose.push(item.userId)
					})
					this.groupList.forEach((item)=>{
						!item.checked&&this.choose.push(item.id)
					})
				}else{
					this.convList.forEach((conv)=>{
						!conv.checked&&this.choose.push(conv.id)
					})
				}
			},
			submit(){
				Promise.all(this.choose.map(async (id)=>{
					const friend = this.friends.find((item)=>item.userId==id)
					let conv = null
					if(friend){
						conv = await this.setConversation({
							id:friend.userId,
							type:ConversationType.Single,
							avatar:friend.avatarUrl,
							name:friend.userName,
							remarks:friend.remarks
						})
					}
					const group = this.groups.find((item)=>item.id==id)
					if(group){
						conv = await this.setConversation({
							id:group.id,
							type:ConversationType.Group,
							avatar:group.avatar,
							name:group.name
						})
					}
					if(conv){
						return this.sendMsg(conv)
					}
				})).then(()=>{
					this.event&&this.event.emit('succeed')
				})
				uni.navigateBack()
			},
		}
	}
</script>
<style>
	page{
		background-color: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
	.checkbox{
		width: 40rpx;
		height: 40rpx;
		background-color: $u-type-info-light;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		transition: all 0.2s ease-out;
		flex-shrink: 0;
		&::after{
			font-family: "cuIcon";
			content: "\e645";
			color: #FFFFFF;
			opacity: 0;
			transition: all 0.2s ease-out;
		}
		&.checked{
			background-color: $u-type-primary;
			&::after{
				opacity: 1;
			}
		}
		&.disable{
			background-color: #aaaaaa;
		}
	}
	.search-mimicry{
		background-color: #F5F5F5;
		padding: 20rpx 30rpx;
		.search-bar{
			height: 90rpx;
			display: flex;
			align-items: center;
			.search{
				display: flex;
				align-items: center;
				flex: 1;
				background-color: #ffffff;
				padding: 10rpx 20rpx;
				border-radius: 10rpx;
			}
			.icon{
				margin-right: 10rpx;
			}
			.input{
				font-size: 32rpx;
				flex: 1;
			}
			.all-in{
				margin-left: 20rpx;
				flex-shrink: 0;
			}
		}
	}
	.group{
		display: flex;
		.checkbox{
			align-self: center;
		}
		.group-avatar{
			flex-shrink: 0;
		}
		.group-content{
			flex: 1;
			overflow: hidden;
		}
	}
	.friend-box{
		&.fold{
			.group:nth-child(n+5){
				display: none;
			}
		}
	}
</style>
